package com.yihong.userserver.controller;

import com.yihong.common.util.AjaxJson;
import com.yihong.common.util.AjaxJsonFactory;
import com.yihong.common.util.JwtUtil;
import com.yihong.userserver.entity.User;
import com.yihong.userserver.service.UserService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName UserController
 * @Description
 * @Author 孟志浩
 * @Date 2019/3/18 11:35
 **/
@RestController
public class UserController {

    /**
     * 日志
     */
    private static  final Logger LOG = LoggerFactory.getLogger(UserController.class);

    /**
     * 用户服务
     */
    @Autowired
    private UserService userService;

    /**
      * 添加用户
      * @param user         添加的实体
      * @param request      请求
      * @return com.yihong.common.util.AjaxJson
      * @author 孟志浩
      * @date 2019/4/2
      **/
    @PostMapping("/user")
    public AjaxJson addUser(@RequestBody User user, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(token);
        Long createId = Long.valueOf(String.valueOf(claims.get("userId")));
        return userService.addUser(user,createId);
    }

    /**
      * 更新用户
      * @param user         用户实体
      * @param request      请求
      * @return com.yihong.common.util.AjaxJson
      * @author 孟志浩
      * @date 2019/4/2
      **/
    @PutMapping("/user")
    public AjaxJson updateUser(@RequestBody User user, HttpServletRequest request){
        if (user.getId() == null || user.getId() == 0) {
            return AjaxJsonFactory.createAjaxJson(500, "提交用户信息异常，用户标识为空");
        }
        String token = request.getHeader("Authorization");
        Long updatorId = JwtUtil.getUserId(token);
        return userService.updateUser(user, updatorId);
    }

    /**
      * 根据条件查询用户
      * @param page         页码
      * @param size         每页数量
      * @param isValid      是否启用
      * @param request      请求
      * @return com.yihong.common.util.AjaxJson
      * @author 孟志浩
      * @date 2019/4/2
      **/
    @GetMapping("/user")
    public AjaxJson listUser(@RequestParam("page") int page, @RequestParam("size") int size,
                             @RequestParam("words")String words, @RequestParam("isValid") int isValid,
                             HttpServletRequest request){
        return userService.findAll(page, size, words, isValid);
    }

    /**
      * 根据id获取用户
      * @param id 用户id
      * @return com.yihong.common.util.AjaxJson
      * @author 孟志浩
      * @date 2019/4/2
      **/
    @GetMapping("/user/{id}")
    public AjaxJson get(@PathVariable("id") Long id) {
        return userService.get(id);
    }

}
